package com.ly.system.util;

import cn.hutool.core.util.StrUtil;
import com.ly.common.core.constant.BaseConstant;
import com.ly.system.system.bean.entity.SysPermission;

/**
 * @author jeecg
 * @Date: 2019-04-03
 */
public class PermissionDataUtil {

    /**
     * 路径：views/
     */
    private static final String PATH_VIEWS = "views/";

    /**
     * 路径：src/views/
     */
    private static final String PATH_SRC_VIEWS = "src/views/";

    /**
     * .vue后缀
     */
    private static final String VUE_SUFFIX = ".vue";

    /**
     * 智能处理错误数据，简化用户失误操作
     *
     * @param permission
     */
    public static SysPermission intelligentProcessData(SysPermission permission) {
        if (permission == null) {
            return null;
        }
        // 组件
        if (StrUtil.isNotEmpty(permission.getComponent())) {
            String component = permission.getComponent();
            if (component.startsWith("/")) {
                component = component.substring(1);
            }
            if (component.startsWith(PATH_VIEWS)) {
                component = component.replaceFirst(PATH_VIEWS, "");
            }
            if (component.startsWith(PATH_SRC_VIEWS)) {
                component = component.replaceFirst(PATH_SRC_VIEWS, "");
            }
            if (component.endsWith(VUE_SUFFIX)) {
                component = component.replace(VUE_SUFFIX, "");
            }
            permission.setComponent(component);
        }
        // 请求URL
        if (StrUtil.isNotEmpty(permission.getUrl())) {
            String url = permission.getUrl();
            if (url.endsWith(VUE_SUFFIX)) {
                url = url.replace(VUE_SUFFIX, "");
            }
            if (!url.startsWith(BaseConstant.STR_HTTP) && !url.startsWith("/") && !url.trim().startsWith("../")) {
                url = "/" + url;
            }
            permission.setUrl(url);
        }
        // 一级菜单默认组件
        if (0 == permission.getMenuType() && StrUtil.isEmpty(permission.getComponent())) {
            // 一级菜单默认组件
            permission.setComponent("layouts/RouteView");
        }
        return permission;
    }
}
